package com.atguigu.gmall.common.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Mamba
 * @version 1.0
 * @Description
 *      拦截器
 *      远程调用请求
 *
 *      工具类
 * @date 2021/1/5 19:34
 */

public class FeignInterceptor implements RequestInterceptor {

    //拦截器方法  RequestTemplate ：远程调用请求对象
    @Override
    public void apply(RequestTemplate requestTemplate) {
        //1：当前请求对象头中用户Id 传递给 远程调用请求对象的头中
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            //当前微服务的请求对象
            HttpServletRequest request = requestAttributes.getRequest();
            if (null != request) {
                //网关传递过来的真实用户Id
                String userId = request.getHeader("userId");
                if (!StringUtils.isEmpty(userId)) {
                    requestTemplate.header("userId", userId);
                }
                //网关传递过来的临时用户Id
                String userTempId = request.getHeader("userTempId");
                if (!StringUtils.isEmpty(userTempId)) {
                    requestTemplate.header("userTempId", userTempId);
                }
            }


        }
    }
}
